package ecom.nopecom.account;

import ecom.nopecom.util.*;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;

import ecom.nopecom.BasePage;
import ecom.nopecom.account.pagecontainer.RegistrationPageContainer;
import org.openqa.selenium.support.ui.Select;

public class Registration extends BasePage {


	
	private static final String REG_CONFIRM_MSG = "ERROR";
			  private static final NopeLogger LOGGER = NopComFactory.getLogger(Registration.class);
	    RegistrationPageContainer pageContainer = PageFactory.initElements(nopeDriver,RegistrationPageContainer.class);
	    public WebDriver driver = NopComFactory.getBrowser();
    private String registerLink = "Register";
    private String maleChkBox = "gender-male";
    private String AddToCart = "//input[@value='Add to cart']";

	    public void register(Consumer consumer)
	    {
            LOGGER.info("Registering the user");
	    	//registerWithMandatoryFields(consumer.getFirstName(),consumer.getLastName(),consumer.getEmail(),consumer.getUsername(),consumer.getPassword());
	    	  register(consumer.getGender(), consumer.getFirstName(), consumer.getLastName(), consumer.getDateOfBirth(), consumer.getUsername(), consumer.getPassword());
	    }



    public void registerWithMandatoryFields(String firstName,
				String lastName, String email, String username, String password) {
			pageContainer.firstName.sendKeys(firstName);
			pageContainer.lastName.sendKeys(lastName);
			pageContainer.email.sendKeys(email);
			pageContainer.username.sendKeys(username);
			pageContainer.password.sendKeys(password);
			clickRegisterButton();
			//nopeDriver.waitForElement("Your registration completed");
			//Assert.assertTrue("Registration failed", nopeDriver.isDisplayed(REG_CONFIRM_MSG));
			
		}
		
		public void clickRegisterButton()
		{
			pageContainer.submit.click();
		}
//	    Asserter asserter = new Asserter(LOGGER);
//	    TermsAndConditions tandcPage = new TermsAndConditions();
//	    CardScreen addCardPage = new CardScreen();
//
//	    private final JacuzziProperties jacuzziProperties = JacuzziProperties.getJacuzziProperties();
//
//
//	    public void selectWalletProvider(String walletProvider) {
//	        selectWalletProvider(WalletProvider.valueForName(walletProvider));
//	    }
//
//	    public void selectWalletProvider(WalletProvider walletProvider) {
//	        LOGGER.info("Selecting Wallet Provider [" + walletProvider.getWalletProviderName() + "]");
//	        navigateSelectWallet();
//	        if (JZDriver.elementExists(walletProvider.getNavigateToElement())) {
//	            LOGGER.info("Wallet Provider element is [" + walletProvider.getNavigateToElement().getAttribute("id") + "]");
//	            JZDriver.waitForTransitionsToComplete();
//	            walletProvider.getNavigateToElement().click();
//	            asserter.assertWithLogging("Continue button display", JZDriver.isDisplayedCheck(pageContainer.continue_button), true);
//	        } else {
//	            throw new IllegalArgumentException("Could not find Wallet Provider element for [" + walletProvider.getWalletProviderName() + "]");
//	        }
//	    }
//
//	    public void navigateSelectWallet() {
//	        LOGGER.info("navigate to select Wallet Providers");
//	        Assert.assertTrue(JZDriver.isDisplayedCheck(pageContainer.select_wallet_button));
//	        pageContainer.select_wallet_button.click();
//	    }
//
//	    public void navigateLearnMoreAbout(String walletProvider) {
//	        LOGGER.info("navigate to more info for '" + walletProvider + "' wallet provider");
//
//	        WebElement readMoreLink = JZDriver.findElement(By.xpath("//*[@id='wallet_providers']//*[text()='" + walletProvider + "']//ancestor::*[contains(@class, 'wallet_provider')]//*[text()='Read more']/parent::a"));
//
//	        LOGGER.info("Selected " + readMoreLink.getText() + " link for " + walletProvider);
//	        Assert.assertTrue(JZDriver.isDisplayedCheck(readMoreLink));
//	        // CNO: need to wait a bit after transitions, since the baseController needs to have a chance to post-process and unblock further transitions
//	        JZDriver.waitFor(400);
//	        readMoreLink.click();
//	    }
//
//	    public void checkWalletProviders(String providers) {
//	        LOGGER.info("check wallet providers");
//	        List<BrandsEnum> expectedProviders = new ArrayList<BrandsEnum>();
//	        StringTokenizer st = new StringTokenizer(providers, ",");
//	        while (st.hasMoreTokens()) {
//	            String provider = st.nextToken();
//	            BrandsEnum expectedProvider = BrandsEnum.findByName(provider.toUpperCase().trim());
//	            Assert.assertNotNull(expectedProvider);
//	            expectedProviders.add(expectedProvider);
//	        }
//	        List<WebElement> actualProviders = pageContainer.wallet_providers;
//
//	        for (WebElement actualProvider : actualProviders) {
//	            boolean found = false;
//	            String actualProviderID = pageContainer.getWalletProviderID(actualProvider);
//	            for (BrandsEnum expectedProvider : expectedProviders) {
//	                if (expectedProvider.getBrandID().equals(actualProviderID)) ;
//	                found = true;
//	            }
//	            Assert.assertTrue("Provider " + actualProviderID + " not found", found);
//	        }
//	        asserter.assertWithLogging("Number of Brands", actualProviders.size(), expectedProviders.size());
//	    }
//
//
//	    public void enterValueIntoOneField(String field, String value) {
//	        FormDataReader.getData(null, LOGGER).enterData(field, getRegistrationWebElement(field), value);
//	        TimeUtils.waitFor(500, "validate whether this wait is needed on [" + field + "] given that we have FormData.enterData() now", LOGGER);
//	    }
//
//	    public void enterValueIntoTwoFields(String firstField, String firstValue, String secondField, String secondValue) {
//	        enterValueIntoOneField(firstField, firstValue);
//	        enterValueIntoOneField(secondField, secondValue);
//	    }
//
//	    public void assertFieldIsMandatory(String labelText) {
//	        Assert.assertTrue(JZDriver.isDisplayed(By.xpath(String.format("//label[abbr[@title='required']]/span[contains(text(), '%s')]", labelText))));
//	    }
//
//	    public void assertFieldIsNotMandatory(String labelText) {
//	        By by = By.xpath(String.format("//label/span[contains(text(), '%s')]//ancestor::label//abbr", labelText));
//
//	        if (JZDriver.elementExists(by)) {
//	            Assert.assertFalse(String.format("Expected field '%s' to be not mandatory", labelText), JZDriver.findElement(by).isDisplayed());
//	        }
//	    }
//
//	    private FormField getRegistrationWebElement(String field) {
//	        LOGGER.info("Field to map: " + field);
//	        HashMap<String, FormField> webElements = pageContainer.getFeatureFriendlyLookupMap();
//	        return webElements.get(field.toUpperCase());
//	    }
//
//	    public void assertPersonalDetailsPane(String pane) {
//	        LOGGER.info("Asserting personal details pane");
//	        Assert.assertTrue(JZDriver.elementExists(pageContainer.accordion_stepone));
//	        LOGGER.info("Element numberOne exists");
//	        Assert.assertTrue(JZDriver.elementExists(pageContainer.accordion_steptwo));
//	        LOGGER.info("Element numberTwo exists");
//	        Assert.assertTrue(JZDriver.elementExists(pageContainer.accordion_stepthree));
//	        LOGGER.info("Element numberThree exists");
//	        if (pane.equalsIgnoreCase("addCard")) {
//	            addCardPage.assertPageDisplayed();
//	        } else {
//	            // Assert registration/personal details page is displayed
//	            this.assertPageDisplayed();
//	        }
//	    }
//
//	    public void submitExistingPersonalDetails(String user) {
//	        if (JZDriver.isDisplayedCheck(pageContainer.continue_button)) {
//	            enterPersonalDetails(user);
//	            LOGGER.info("Submitting personal details");
//	            pageContainer.continue_button.click();
//	            JZDriver.waitForTransitionsToComplete();
//	        } else {
//	            Assert.fail("Registration continue button isn't showing");
//	        }
//
//	        assertPersonalDetailsPane("registration");
//	    }
//
//	    public void submitPersonalDetails(String user) {
//	        if (JZDriver.isDisplayedCheck(pageContainer.continue_button)) {
//	            enterPersonalDetails(user);
//	            LOGGER.info("Submitting personal details");
//	            pageContainer.continue_button.click();
//	            Boolean paneFound = Poller.start().pollUntilConditionIsSatisfied(new ElementIsDisplayed(addCardPage.getPageDisplayedCheckElement()));
//	            Assert.assertTrue("Add card pane is not displayed", paneFound);
//	            JZDriver.waitForTransitionsToComplete();
//	        } else {
//	            Assert.fail("Registration continue button isn't showing");
//	        }
//
//	        if (user != null) {
//	            success();
//	        }
//	    }
//
//	    public void submitPersonalDetails() {
//	        submitPersonalDetails(null);
//	    }
//
//	    public void registerPersonalDetailsWithPortalUserFromPreviousStep() {
//	        if (JZDriver.isDisplayedCheck(pageContainer.continue_button)) {
//	            PortalUser portalUser = PortalUserProvider.getPortalUser();
//	            LOGGER.info("Enter Personal Details [" + portalUser.toString() + "]");
//	            enterUserName(portalUser);
//	            enterPhoneAndPassword(portalUser);
//	            acceptTnC();
//	            LOGGER.info("Continuing after T&Cs");
//	            pageContainer.continue_button.click();
//	            JZDriver.waitForTransitionsToComplete();
//	        } else {
//	            Assert.fail("Registration continue button isn't showing");
//	        }
//	    }
//
//	    public void enterPersonalDetails(String user) {
//	        LOGGER.info("Entering personal details");
//	        PortalUser portalUser = null;
//	        try {
//	            portalUser = (user == null) ? newPortalUser() : newPortalUserFromProperties(user);
//	        } catch (JacuzziConfigurationException e) {
//	            Assert.fail("JacuzziConfigurationException thrown when getting portal user. " + e.getMessage());
//	        } catch (Exception e) {
//	            Assert.fail("Exception thrown when getting portal user. " + e.getMessage());
//	        }
//	        enterUserName(portalUser);
//	        enterPhoneAndPassword(portalUser);
//	        acceptTnC();
//	    }
//
//	    public void enterPersonalDetails() {
//	        enterPersonalDetails(null);
//	    }
//
//	    public void acceptTnC() {
//	        pageContainer.ts_and_cs_checkbox.click();
//	    }
//
//	    public void assertOnPersonalDetails() {
//	        PortalUser portalUser = PortalUserProvider.getPortalUser();
//	        Assert.assertEquals(portalUser.getUsername(), pageContainer.username_input.getAttribute("value"));
//	        Assert.assertEquals(portalUser.getUsername(), pageContainer.usernameConfirmation_input.getAttribute("value"));
//	        Assert.assertEquals(CountriesEnum.toCountryCode(portalUser.getMobileCode()), pageContainer.country_code_select.getAttribute("value"));
//	        Assert.assertEquals(portalUser.getMobileNumber(), pageContainer.mobile_number_input.getAttribute("value"));
//	        Assert.assertEquals(portalUser.getPassword(), pageContainer.password_input.getAttribute("value"));
//	        Assert.assertEquals(portalUser.getPassword(), pageContainer.confirm_password_input.getAttribute("value"));
//	        Assert.assertTrue(pageContainer.ts_and_cs_checkbox.isSelected());
//	    }
//
//	    public void assertOnDisplayedPage(String pageId) {
//	        LOGGER.info("Assert on displayed page: '" + pageId + "'");
//	        JZDriver.isDisplayed(JZDriver.findElement(By.id(pageId)));
//	    }
//
//	    public void registerAndLogout(PortalUser portalUser) {
//	        LOGGER.info("Entering personal details of new user");
//	        if (JZDriver.isDisplayedCheck(pageContainer.continue_button)) {
//	            enterUserName(portalUser);
//	            enterPhoneAndPassword(portalUser);
//	            acceptTnC();
//	            pageContainer.continue_button.click();
//	            LOGGER.info("Submitting personal details");
//	        }
//	        success();
//	        JZDriver.waitFor(1000); // arrgh another one of these b***ers required
//	        pageContainer.close_button.click();
//	        pageContainer.logout_button.click();
//	        PortalUserProvider.walletRefreshRequired();
//	        new Session().launchCheckoutWithMerchant("JZ1");
//	    }
//
//	    public void success() {
//	        assertPersonalDetailsPane("addCard");
//	    }
//
//	    public void enterUserName(PortalUser portalUser) {
//	        LOGGER.info("Entering user name [" + portalUser.getUsername() + "]");
//	        pageContainer.username_input.sendKeys(portalUser.getUsername());
//	        pageContainer.usernameConfirmation_input.sendKeys(portalUser.getUsername());
//	    }
//
//	    private void enterPhoneAndPassword(PortalUser portalUser) {
//	        JZDriver.sendKeys(pageContainer.country_code_select, portalUser.getMobileCode());
//	        pageContainer.mobile_number_input.sendKeys(portalUser.getMobileNumber());
//	        pageContainer.password_input.sendKeys(portalUser.getPassword());
//	        pageContainer.confirm_password_input.sendKeys(portalUser.getPassword());
//	    }
//
//	    public void verifyValidationError(String errorMessage) {
//	        validationErrorChecker.checkErrors(pageContainer.getFeatureFriendlyLookupMap(), errorMessage);
//	    }
//
//	    public boolean failedWithError(String expectedError) {
//	        LOGGER.info("Verifying log in failed");
//
//	        List<WebElement> errorList = JZDriver.findElements(By.className("serviceLayerErrorMsg"));
//	        for (WebElement webElement : errorList) {
//	            LOGGER.info("Webelement error text: " + webElement.getText());
//	            boolean value = JZDriver.verifyAttributeValue(webElement, "data-servicelayermessageid", expectedError.trim());
//	            LOGGER.info("verification of attribute is: " + value);
//	            return value;
//	        }
//
//	        return false;
//	    }
//
//
//	    public void assertOnInputFieldValue(String labelText, String expectedValue) {
//	        WebElement input = this.pageContainer.getInputFieldByLabelText(labelText);
//	        Assert.assertNotNull("Specified input field couldn't be found: " + labelText, input);
//
//	        String tagName = input.getTagName();
//	        LOGGER.info(String.format("Assert on value of a '%s' field", tagName));
//
//	        if (tagName.equals("input")) {
//	            Assert.assertEquals(expectedValue, input.getAttribute("value"));
//	        }
//	    }
//
//	    public void selectTandCLink() {
//	        WebElement linkElement = JZDriver.waitForElement(pageContainer.tandc_link);
//	        Assert.assertNotNull("Unable to find the T and C link on the page", linkElement);
//	        linkElement.click();
//	    }
//
//	    @Override
//	    public WebElement getPageDisplayedCheckElement() {
//	        return pageContainer.main_page_div;
//	    }
//
//	    public String getSessionIdFromMerchantResponse() {
//	        String sessionId = "NOT_FOUND";
//	        if (JZDriver.isDisplayed(By.id("merchantForm:j_id6:tbody_element"))) {
//	            sessionId = JZDriver.findElement(By.xpath("//form/div/div/table/tbody/tr[3]/td")).getText()
//	                    .replace("<SessionID>", "").replace("</SessionID>", "");
//	        }
//	        LOGGER.info("Session Id from Merchant Response was [" + sessionId + "]");
//	        return sessionId;
//	    }
public void register(char gender, String firstName, String lastName,
                     String dateOfBirth, String email, String password) {

    driver.findElement(By.linkText(registerLink)).click();
    if(gender=='M')
        driver.findElement(By.id("gender-male")).click();
    else
        driver.findElement(By.id("gender-female")).click();
    driver.findElement(By.id("FirstName")).clear();
    driver.findElement(By.id("FirstName")).sendKeys(firstName);
    driver.findElement(By.id("LastName")).clear();
    driver.findElement(By.id("LastName")).sendKeys(lastName);
    new Select(driver.findElement(By.name("DateOfBirthDay"))).selectByVisibleText(dateOfBirth.split("/")[0]);
    new Select(driver.findElement(By.name("DateOfBirthMonth"))).selectByVisibleText(dateOfBirth.split("/")[1]);
    new Select(driver.findElement(By.name("DateOfBirthYear"))).selectByVisibleText(dateOfBirth.split("/")[2]);
    driver.findElement(By.id("Email")).clear();

    driver.findElement(By.id("Email")).sendKeys(email);
    driver.findElement(By.id("Password")).clear();
    driver.findElement(By.id("Password")).sendKeys(password);
    driver.findElement(By.id("ConfirmPassword")).clear();
    driver.findElement(By.id("ConfirmPassword")).sendKeys(password);
    driver.findElement(By.id("register-button")).click();
    SystemLibrary.waitFor(3);
//    WebElement errorElement = driver.findElement(By.className("validation-summary-errors"));
    if(NopeDriver.isElementAndTextPresent(By.className("validation-summary-errors"), "The specified email already exists"))
    {
        driver.findElement(By.id("Email")).clear();
        driver.findElement(By.id("Email")).sendKeys(TestDataGenerator.withAlphanumerics(4)+"@email.com");
        driver.findElement(By.id("register-button")).click();
        SystemLibrary.waitFor(3);
    }

    Assert.assertTrue(driver.getPageSource().contains("Your registration completed"));
}


	@Override
	public WebElement getLandingElement() {
		// TODO Auto-generated method stub
		return null;
	}
	
	

}
